package cn.com.dhc.danlu.business.shopcar.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.base.DanluBaseActivity;
import cn.com.dhc.danlu.activity.delivery.OrderConfirmActivity;
import cn.com.dhc.danlu.business.shopcar.adapter.ShopCarAdapter;
import cn.com.dhc.danlu.business.shopcar.bean.MerchBean;
import cn.com.dhc.danlu.business.shopcar.bean.PromotionBean;
import cn.com.dhc.danlu.business.shopcar.bean.SellerBean;
import cn.com.dhc.danlu.business.shopcar.bean.WrapDealerAttr;
import cn.com.dhc.danlu.business.shopcar.callback.IDataChangeCallback;
import cn.com.dhc.danlu.business.shopcar.delegate.ShopCarListDelegate;
import cn.com.dhc.danlu.business.shopcar.popup.PromotionSelectPopup;
import cn.com.dhc.danlu.business.shopcar.view.BottomSheetTipsDialog;
import cn.com.dhc.danlu.business.shopcar.view.ShopPayActionBtn;
import cn.com.dhc.danlu.delegate.callback.IListDataCallback;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.ShoppingCartCommitModel;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.GsonFactory;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.DanluRecyclerView;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.OnChangedPromotionInfoRequest;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.PreViewOrderRequest;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.PreViewOrderRequest.ToSettlementModel.MerchListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.GiftListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.OnChangedPromotionInfoResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.PreViewOrderResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ToShoppingcartResponse.SellerListBean.MerchListBean.PromotionModelListBean;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.WebservicesConst.BUSINESS_SUCCESS_YES;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-03-09 04:32<br/>
 * <p>
 * <p>
 * 购物车界面
 * </p>
 */
public class ShopCarActivity extends DanluBaseActivity implements IListDataCallback, IDataChangeCallback {
    public static final String FROM_ACTIVITY_FLAG = "fromActivityFlag";
    public static final int FROM_GOOD_INFO = 0x2;
    private static final int FROM_MAIN_MENU = 0x1;
    private int fromActivityFlag;

    private ImageView ivSelall;
    private TextView tvTotalPrice;
    private ShopPayActionBtn btnCommit;
    private DanluRecyclerView drShoppingList;
    private LoaddingLayout llLoading;
    private PromotionSelectPopup promotionSelectPopup;

    private ShopCarAdapter adapter;
    private ShopCarListDelegate delegate;

    // 记录商品存量（初始化数据、删除数据等等），用于标识是否显示空视图
    private int merchLeftCount;

    // 原始总价
    private BigDecimal totalPrice;
    // 优惠后的总价
    private BigDecimal fixTotalPrice;

    // 存储商品ID与已选促销之间的映射
    private HashMap<String, PromotionModelListBean> merchPromotionMap;
    // 存储商品ID与商品所有的促销之间的映射
    private HashMap<String, String> merchPromotionLimitNumberMap;
    // 存储商品ID与已选促销模型后网络访问返回的响应体之间的映射
    private HashMap<String, OnChangedPromotionInfoResponse> merchChangePromotionMap;

    // 选中标志位
    private boolean isCanPay;
    private boolean isInEditMode;
    private boolean isSelectAllEdit;
    private boolean isSelectAllNormal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_car);

        initArgs();
        initViews();
        setViews();
        initApis();
    }

    @Override
    protected void onResume() {
        super.onResume();

        isInEditMode = false;
        btnCommit.setText(getString(R.string.shop_cart_commit_label));

        if (this.merchLeftCount == 0) {
            mToolbar.setRightTxt("");
            llLoading.showLoaddingView();
            loadData();
        } else {
            mToolbar.setRightTxt(R.string.shoppingcart_btn_edit);
            drShoppingList.scrollToPosition(0);
            drShoppingList.postDelayed(new Runnable() {
                @Override
                public void run() {
                    drShoppingList.setRefreshing();
                    loadData();
                }
            }, 300);
        }
    }

    private void initArgs() {
        fromActivityFlag = getIntent().getIntExtra(FROM_ACTIVITY_FLAG, FROM_MAIN_MENU);
        merchPromotionMap = new HashMap<>();
        merchChangePromotionMap = new HashMap<>();
        merchPromotionLimitNumberMap = new HashMap<>();
    }

    private void initViews() {
        ivSelall = (ImageView) findViewById(R.id.iv_selall);
        tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        btnCommit = (ShopPayActionBtn) findViewById(R.id.btn_commit);
        drShoppingList = (DanluRecyclerView) findViewById(R.id.dr_shopping_list);
        llLoading = (LoaddingLayout) findViewById(R.id.ll_loading);
    }

    private void setViews() {
        llLoading.isShowEmptyRetryBtn(false);
        llLoading.setEmptyPic(R.drawable.img_shoppingcar_nodata);
        btnCommit.setCanPay(true);
        drShoppingList.postDelayed(new Runnable() {
            @Override
            public void run() {
                drShoppingList.setRefreshing();
            }
        }, 200);
        drShoppingList.setLoadingMoreEnabled(false);

        ivSelall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInEditMode) {
                    isSelectAllEdit = !isSelectAllEdit;
                    ivSelall.setSelected(isSelectAllEdit);
                    adapter.selectAll(isSelectAllEdit);
                } else {
                    isSelectAllNormal = !isSelectAllNormal;
                    ivSelall.setSelected(isSelectAllNormal);
                    adapter.selectAll(isSelectAllNormal);
                }
            }
        });

        switch (fromActivityFlag) {
            case FROM_GOOD_INFO:
                mToolbar.setBackVisible(true);
                mToolbar.setBackImg(R.drawable.ic_back);
                break;

            case FROM_MAIN_MENU:
            default:
                mToolbar.setBackVisible(false);
                break;
        }
        mToolbar.setRightClickListenter(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isInEditMode = !isInEditMode;
                if (isInEditMode) {
                    mToolbar.setRightTxt(R.string.shoppingcart_btn_finish);
                    btnCommit.setText(getString(R.string.shop_cart_delete_label));
                    btnCommit.setCanPay(true);
                    ivSelall.setSelected(isSelectAllEdit);
                } else {
                    mToolbar.setRightTxt(R.string.shoppingcart_btn_edit);
                    btnCommit.setText(getString(R.string.shop_cart_commit_label));
                    btnCommit.setCanPay(isCanPay);
                    ivSelall.setSelected(isSelectAllNormal);

                    if (merchLeftCount == 0) {
                        mToolbar.setRightTxt("");
                        llLoading.showEmptyView(getString(R.string.shopping_cart_nodata_tip));
                    }
                }
                if (null == adapter) {
                    return;
                }
                adapter.setInEdited(isInEditMode);
                adapter.setSelAllState();
                drShoppingList.setPullRefreshEnabled(!isInEditMode);
            }
        });
        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (merchLeftCount > 0) {
                    if (isInEditMode) {
                        // 编辑状态下 删除选中项
                        adapter.delSelItems();
                        ivSelall.setSelected(false);
                    } else {
                        if (btnCommit.isCanPay()) {
                            // 非编辑 可支付状态下 支付选中商品
                            payForSelItems();
                        } else {
                            // 非编辑 不可支付状态下 弹窗提示用户不满足条件
                            popupWaring(adapter.getCannotPaySeller());
                        }
                    }
                }
            }
        });
        drShoppingList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                CommonUtils.hideSoftInputForce(ShopCarActivity.this);
                return false;
            }
        });
    }

    /**
     * 显示警告用户不满足支付条件的窗口
     *
     * @param cannotPaySeller 没有支付资格的商家 index 集合
     */
    private void popupWaring(List<WrapDealerAttr> cannotPaySeller) {
        // TODO: 2017/3/9 显示一个 popupwindow #ok
        // 1. 传入不满足条件的商家 list 数据源
        // 2. 丢到 popupwindow 中
        BottomSheetTipsDialog cannotPayDialog = new BottomSheetTipsDialog(this);
        cannotPayDialog.refreshContent(cannotPaySeller);
        cannotPayDialog.show();
    }

    /**
     * 获取选中的商品名称并支付
     */
    private void payForSelItems() {
        // TODO: 2017/3/9 完成这里 @lyf #ok
        // 1. 获取所有选中的数据
        final SparseArray<List<Integer>> sellerMerchMap = adapter.getSellerMerchMap();
        if (sellerMerchMap.size() == 0) {
            ToastUtil.getInstance().show(R.string.shopping_cart_tip_noselected_goods);
        } else {
            // 2. 组装成清单数据原型
            // 3. 发起网络请求
            agent.getApi()
                    .getPreViewOrderByShoppingCart(getPreViewOrderRequest(sellerMerchMap))
                    .compose(OperatorUtils.<PreViewOrderResponse>defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<PreViewOrderResponse>(ShopCarActivity.this, R.string.tips_settle_accounts) {
                        @Override
                        protected void onSuccess(PreViewOrderResponse model) {
                        }

                        @Override
                        public void onNext(PreViewOrderResponse model) {
                            // 3. 将数据原型传递至下一层界面
                            if (model.getSuccess().equals(BUSINESS_SUCCESS_YES)) {
                                ShoppingCartCommitModel shoppingCartCommitModel = new ShoppingCartCommitModel();
                                // 待传递的已选购物车数据模型
                                shoppingCartCommitModel.setSellerList(getSelectedStoreModel(sellerMerchMap));
                                shoppingCartCommitModel.setToSettlementInfoModel(model.getToSettlementInfoModel());
                                String strModel = GsonFactory.getGson().toJson(shoppingCartCommitModel);
                                // 跳转至订单确认画面
                                Intent intent = new Intent();
                                // 跳转画面：订单确认画面
                                intent.setClass(ShopCarActivity.this, OrderConfirmActivity.class);
                                // 购物车结算模型
                                intent.putExtra(CommonConst.IntentKey.SHOPPING_CART_COMMIT_MODEL, strModel);
                                intent.putExtra(CommonConst.IntentKey.CART_COMMIT_PROMOTION_MODEL, merchPromotionMap);
                                intent.putExtra(CommonConst.IntentKey.CART_COMMIT_PROMOTION_VALUE_MODEL, merchChangePromotionMap);
                                // 传递参数：是否是从未支付订单画面跳转
                                intent.putExtra(CommonConst.IntentKey.IS_ORDER, false);
                                intent.putExtra("totalPrice", fixTotalPrice.toPlainString());
                                intent.putExtra("origintotalprice", totalPrice.toPlainString());
                                startActivity(intent);
                            } else {
                                showCommitFailedReasons(model.getFailedReasons());
                            }
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(displayMessage);
                        }
                    });
        }
    }

    /**
     * 显示结算失败详情对话框
     */
    private void showCommitFailedReasons(PreViewOrderResponse.FailedReasonsBean failedReasons) {
        if (failedReasons == null) {
            ToastUtil.getInstance().show(R.string.commit_error_goods_tip);
            return;
        }
        StringBuilder sbErrorInfo = new StringBuilder();
        // 商品数量不能小于起购数量
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getLessThanMiniStartSaleQuantityList(), R.string.cart_reachMiniStartSaleQuantity_tips);
        // 商品被删除提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getDelList(), R.string.commit_error_goods_deleted);
        // 商品无效提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getInvalidList(), R.string.commit_error_goods_invalid);
        // 商品名改变提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNameChangedList(), R.string.commit_error_goods_name_changed);
        // 商品在购物车中不存在
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNotExistsList(), R.string.commit_error_shop_car_goods_deleted);
        // 商品缺货提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNoInventoryList(), R.string.commit_error_goods_no_inventory);
        // 商品库存不足提示
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNoOnHandInventoryList(), R.string.commit_error_goods_no_onhandinventory);
        // 卖家增值税发票权限变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getNoSupplyInvoicList(), R.string.commit_error_goods_no_supplyinvoic);
        // 商品价格发生变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getPriceChangedList(), R.string.commit_error_goods_price_changed);
        // 促销信息发生变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getPromotiontChangedList(), R.string.commit_error_goods_promotion_changed);
        // 商品已下架
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getShelvesOffList(), R.string.commit_error_goods_shelves_off);
        // 商品规格变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getSpecChangedList(), R.string.commit_error_goods_spec_changed);
        // 支付方式发生变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getSupplyCodPaymentChangedList(), R.string.commit_error_goods_supply_codpayment_changed);
        // 限购条件发生了变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getPromotionLimitList(), R.string.commit_error_goods_promotion_limit_changed);
        // 限购额度变为0
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getPromotionLimitQuotaList(), R.string.commit_error_goods_promotion_limit_quotaout);
        //经销商起送金额变化
        buildCommitErrorMsg(sbErrorInfo, failedReasons.getDeliveryAmountChangedList(), R.string.commit_error_goods_min_amount_changed);
        if (sbErrorInfo.length() < 1) {
            ToastUtil.getInstance().show(R.string.commit_error_goods_tip);
            return;
        }

        // 创建Builder
        ViewDialog.Builder builder = new ViewDialog.Builder(ShopCarActivity.this);
        // 设置标题
        builder.setTitle(R.string.prompt_label);
        // 设置信息
        builder.setMessage(sbErrorInfo.toString());
        // 设置Positive按钮点击监听
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 对话框关闭
                dialog.dismiss();
                onResume();
                sendBroadcast(new Intent(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_COUNT_ACTION));
            }
        });
        // 创建对话框并显示
        builder.create().show();
    }

    /**
     * 构建购物车结算失败提示信息
     */
    private void buildCommitErrorMsg(StringBuilder sb, List<String> itemList, int resStrId) {
        if (itemList != null && itemList.size() > 0) {
            for (String item : itemList) {
                sb.append(item);
                sb.append("\n");
            }
            sb.append(getString(resStrId));
            sb.append("\n");
        }
    }

    /**
     * 组装成清单数据原型
     *
     * @param sellerMerchMap 商家机商品选中映射表
     * @return PreViewOrderRequest
     */
    private PreViewOrderRequest getPreViewOrderRequest(SparseArray<List<Integer>> sellerMerchMap) {
        PreViewOrderRequest request = new PreViewOrderRequest();
        request.setToken(agent.getToken());
        List<PreViewOrderRequest.ToSettlementModel> toSettlementModelList = new ArrayList<>();

        for (int i = 0; i < sellerMerchMap.size(); i++) {
            PreViewOrderRequest.ToSettlementModel toSettlementModel = new PreViewOrderRequest.ToSettlementModel();
            if (adapter.getDatas().get(sellerMerchMap.keyAt(i)) instanceof SellerBean) {
                SellerBean sellerBean = (SellerBean) adapter.getDatas().get(sellerMerchMap.keyAt(i));
                toSettlementModel.setCodFlag(sellerBean.getCodFlag());
                toSettlementModel.setIsYijipayAccount(sellerBean.getIsYijipayAccount());
                toSettlementModel.setPaymentFlag(sellerBean.getPaymentFlag());
                toSettlementModel.setSellerId(sellerBean.getSellerId());
                toSettlementModel.setSellerName(sellerBean.getSellerName());
                toSettlementModel.setSupportVatInvoice(sellerBean.getSupportVatInvoice());

                List<MerchListBean> merchList = new ArrayList<>();
                for (Integer index : sellerMerchMap.valueAt(i)) {
                    if (adapter.getDatas().get(index) instanceof MerchBean) {
                        MerchBean merchBean = (MerchBean) adapter.getDatas().get(index);
                        MerchListBean merch = new MerchListBean();

                        merch.setId(merchBean.getId());
                        merch.setMerchBarCode(merchBean.getMerchBarCode());
                        merch.setMerchId(merchBean.getMerchId());
                        merch.setMerchName(merchBean.getMerchName());

                        if (merchBean.isSelPromotion()) {
                            PromotionModelListBean promotion = merchBean.getPromotionModelList().get(merchBean.getSelPromotionIndex());
                            merch.setPromotionDetail(promotion.getPromotionInfo());
                            merch.setPromotionType(promotion.getPromotionType());
                            merch.setPromotionId(promotion.getPromotionId());
                            merch.setReductionFlg(promotion.getReductionType());
                            merch.setRuleId(promotion.getRuleId());

                            if (CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4.equals(promotion.getPromotionType())) {
                                merch.setLimitRuleList(merchPromotionMap.get(merch.getMerchId()).getLimitRuleList());
                                merch.getLimitRuleList().get(0).setLimitNumber(merchPromotionLimitNumberMap.get(merch.getMerchId()));
                            }
                        }

                        merchList.add(merch);
                    }
                }

                toSettlementModel.setMerchList(merchList);
            }
            toSettlementModelList.add(toSettlementModel);
        }

        request.setToSettlementModel(toSettlementModelList);
        return request;
    }

    private void initApis() {
        delegate = new ShopCarListDelegate();
        delegate.attachHostView(this);
        delegate.setRefreshViewAttr(drShoppingList);
        drShoppingList.setRefreshView(delegate);
    }

    private void loadData() {
        if (null != merchPromotionMap) {
            merchPromotionMap.clear();

        }
        if (null != merchChangePromotionMap) {
            merchChangePromotionMap.clear();
        }
        if (null != merchPromotionLimitNumberMap) {
            merchPromotionLimitNumberMap.clear();
        }
        delegate.fetchData(true);
    }

    @Override
    public void onSuccess(@NonNull List datas, boolean isRefresh) {
        if (datas.isEmpty()) {
            this.merchLeftCount = 0;
            mToolbar.setRightTxt("");
            llLoading.showEmptyView(getString(R.string.shopping_cart_nodata_tip));
        } else {
            this.merchLeftCount = 1;
            mToolbar.setRightTxt(R.string.shoppingcart_btn_edit);
            llLoading.showContentView();
            adapter = new ShopCarAdapter(this, this);
            drShoppingList.setAdapter(adapter);
            adapter.refreshAllData(datas);
            // 设置能否支付状态
            isCanPay = adapter.getCannotPaySeller().isEmpty();
            btnCommit.setCanPay(isCanPay);
        }
        drShoppingList.refreshComplete();
    }

    @Override
    public void onError(@NonNull String errorInfo, boolean isRefresh) {
        mToolbar.setRightTxt("");
        llLoading.showEmptyView(errorInfo);
        ToastUtil.getInstance().show(errorInfo);
        drShoppingList.refreshComplete();
    }

    @Override
    public void onSelAll(boolean isSelAll) {
        ivSelall.setSelected(isSelAll);
    }

    @Override
    public void onTotalPriceChange(BigDecimal fixTotalPrice, BigDecimal totalPrice) {
        tvTotalPrice.setText(CommonUtils.fenToYuan(fixTotalPrice).toPlainString());

        this.totalPrice = totalPrice;
        this.fixTotalPrice = fixTotalPrice;
    }

    @Override
    public void onCanPay(boolean isCanPay) {
        if (isInEditMode) {
            btnCommit.setCanPay(true);
        } else {
            this.isCanPay = isCanPay;
            btnCommit.setCanPay(this.isCanPay);
        }
    }

    @Override
    public void showPromotionSelect(final int merchIndex) {
        // FIXME: 2017/3/12 解决 popupwindow 没有阴影的问题 @lyf #ok
        Activity context;
        if (fromActivityFlag == FROM_MAIN_MENU) {
            context = ShopCarActivity.this.getParent();
        } else {
            context = ShopCarActivity.this;
        }
        final MerchBean merch = (MerchBean) adapter.getDatas().get(merchIndex);
        promotionSelectPopup = new PromotionSelectPopup(context, (ViewGroup) context.getWindow().getDecorView(), merch.getPromotionModelList(), merch.getSelPromotionIndex());
        promotionSelectPopup.setNeedAnim(true);
        promotionSelectPopup.showAtLocation(context.getWindow().getDecorView(), Gravity.CENTER, 0, CommonUtils.getStatusBarHeight(context));
        promotionSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 1. 上报服务器
                updatePromotion(merch, promotionSelectPopup.getPromotionSelIndex());
            }
        });
    }

    @Override
    public void onDelfailed() {
        drShoppingList.scrollToPosition(0);
        drShoppingList.postDelayed(new Runnable() {
            @Override
            public void run() {
                drShoppingList.setRefreshing();
                loadData();
            }
        }, 200);
    }

    @Override
    public void onDelSuccess(int merchLeftCount) {
        sendBroadcast(new Intent(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_COUNT_ACTION));
        this.merchLeftCount = merchLeftCount;
    }

    /**
     * 更新优惠信息
     *
     * @param merch             商品信息
     * @param promotionSelIndex 选中的促销 index
     */
    private void updatePromotion(final MerchBean merch, final int promotionSelIndex) {
        if (merch.isValidPromotion(promotionSelIndex) && promotionSelIndex != merch.getSelPromotionIndex()) {
            // 如果是有效促销信息
            // 2. 在 onSuccess 中更新对应的UI
            // 构建请求参数
            PromotionModelListBean promotionModelListBean = merch.getPromotionModelList().get(promotionSelIndex);
            final OnChangedPromotionInfoRequest request = new OnChangedPromotionInfoRequest();
            request.setToken(agent.getToken());
            request.setMerchId(merch.getMerchId());
            request.setPromotionId(promotionModelListBean.getPromotionId());
            request.setPromotionType(promotionModelListBean.getPromotionType());
            request.setRuleId(promotionModelListBean.getRuleId());
            // 满增-不传 满减-必须 满减类型 0-减单价 1-减总额
            if (CommonConst.PromotionConst.PROMOTION_TYPE_1.equals(promotionModelListBean.getPromotionType())) {
                // 满减
                request.setReductionType(promotionModelListBean.getReductionType());
            } else {
                // 满赠
                request.setReductionType(null);
            }

            // 发起网络访问
            agent.getApi()
                    .getOnChangedPromotionInfo(request)
                    .compose(OperatorUtils.<OnChangedPromotionInfoResponse>defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<OnChangedPromotionInfoResponse>(this, R.string.tips_change_promotion_info) {
                        @Override
                        protected void onSuccess(OnChangedPromotionInfoResponse response) {
                            PromotionModelListBean promotion = merch.getPromotionModelList().get(promotionSelIndex);
                            merchPromotionMap.put(merch.getMerchId(), promotion);
                            merchChangePromotionMap.put(merch.getMerchId(), response);

                            promotion.setDiffPrice(response.getDiffPrice());
                            promotion.setIsPromotion(response.getIsPromotion());

                            if (!TextUtils.isEmpty(response.getIsPromotion())) {
                                promotion.setIsPromotion(response.getIsPromotion());
                            }

                            if (!TextUtils.isEmpty(response.getPromotionType())) {
                                switch (response.getPromotionType()) {
                                    case CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1:
                                        // 满减单
                                        promotion.setPromotionType(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1);
                                        promotion.setReductionType(CommonConst.PromotionConst.REDUCTION_TYPE_0);
                                        break;

                                    case CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_2:
                                        // 满减总
                                        promotion.setPromotionType(CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_1);
                                        promotion.setReductionType(CommonConst.PromotionConst.REDUCTION_TYPE_1);
                                        break;

                                    case CommonConst.PromotionConst.PROMOTION_CHANGE_TYPE_4:
                                        if (!merchPromotionLimitNumberMap.containsKey(merch.getMerchId())) {
                                            merchPromotionLimitNumberMap.put(merch.getMerchId(), promotion.getLimitRuleList().get(0).getLimitNumber());
                                        }
                                        // 限购
                                        promotion.setPromotionType(response.getPromotionType());
                                        promotion.getLimitRuleList().get(0).setLimitNumber(response.getLimitTimesLeft());
                                        break;

                                    default:
                                        // 满赠
                                        promotion.setPromotionType(response.getPromotionType());
                                        if (!TextUtils.isEmpty(response.getPresentationDetail())) {
                                            // 满赠促销语
                                            promotion.setPresentationDetail(response.getPresentationDetail());
                                        }
                                        break;
                                }
                            }

                            noticeAdapter(merch, promotionSelIndex, response.getGiftList());
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(displayMessage);
                        }
                    });
        } else if (promotionSelIndex == merch.getPromotionModelList().size()) {
            // 如果是选中的最后一项
            if (promotionSelIndex != merch.getSelPromotionIndex()) {
                merchPromotionMap.remove(merch.getMerchId());
                merchChangePromotionMap.remove(merch.getMerchId());

                noticeAdapter(merch, promotionSelIndex, null);
            }
        }
    }

    private void noticeAdapter(MerchBean merch, int selectIndex, List<GiftListBean> giftList) {
        merch.setSelPromotionIndex(selectIndex);
        adapter.updateMerchPromotion(merch, giftList);
    }

    /**
     * 是否有在显示 popupwindow
     *
     * @return true - 有
     */
    public boolean isShowPopupWindow() {
        return null != promotionSelectPopup && promotionSelectPopup.isShowing();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK && isShowPopupWindow()) {
            promotionSelectPopup.dismiss();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取转换后的数据包装
     *
     * @param sellerMerchMap 商家商品映射表
     * @return 商家数据集合
     */
    private List<SellerListBean> getSelectedStoreModel(SparseArray<List<Integer>> sellerMerchMap) {
        List<ToShoppingcartResponse.SellerListBean> selectedStoreModel = new ArrayList<>();
        for (int i = 0; i < sellerMerchMap.size(); i++) {
            if (adapter.getDatas().get(sellerMerchMap.keyAt(i)) instanceof SellerBean) {
                SellerBean sellerBean = (SellerBean) adapter.getDatas().get(sellerMerchMap.keyAt(i));
                SellerListBean sellerListBean = new SellerListBean();

                sellerListBean.setPaymentFlag(sellerBean.getPaymentFlag());
                sellerListBean.setSellerId(sellerBean.getSellerId());
                sellerListBean.setSellerName(sellerBean.getSellerName());
                sellerListBean.setSupportCod(sellerBean.getSupportCod());
                sellerListBean.setCodFlag(sellerBean.getCodFlag());
                sellerListBean.setSupportVatInvoice(sellerBean.getSupportVatInvoice());
                sellerListBean.setIsYijipayAccount(sellerBean.getIsYijipayAccount());
                sellerListBean.setPromotionBean(((PromotionBean) adapter.getDatas().get(sellerBean.getPromotionIndex())).getPromotion());

                List<ToShoppingcartResponse.SellerListBean.MerchListBean> merchList = new ArrayList<>();
                for (Integer index : sellerMerchMap.valueAt(i)) {
                    if (adapter.getDatas().get(index) instanceof MerchBean) {
                        MerchBean merchBean = (MerchBean) adapter.getDatas().get(index);
                        ToShoppingcartResponse.SellerListBean.MerchListBean merch = new SellerListBean.MerchListBean();

                        merch.setId(merchBean.getId());
                        merch.setMerchBarCode(merchBean.getMerchBarCode());
                        merch.setMerchId(merchBean.getMerchId());
                        merch.setMerchName(merchBean.getMerchName());
                        merch.setMerchQuantity(merchBean.getMerchQuantity());
                        merch.setMerchStatus(merchBean.getMerchStatus());
                        merch.setOnHandInventory(merchBean.getOnHandInventory());
                        merch.setPriceRetail(merchBean.getPriceRetail());
                        merch.setSellerId(merchBean.getSellerId());
                        merch.setSellerName(merchBean.getSellerName());
                        merch.setSpecName(merchBean.getSpecName());
                        merch.setUnitPrice(merchBean.getUnitPrice());
                        merch.setReturnFlag(merchBean.getReturnFlag());
                        merch.setPicUrl(merchBean.getPicUrl());
                        merch.setMiniStartSaleQuantityChanged(merchBean.getMiniStartSaleQuantityChanged());

                        merchList.add(merch);
                    }
                }

                sellerListBean.setMerchList(merchList);
                selectedStoreModel.add(sellerListBean);
            }
        }

        return selectedStoreModel;
    }
}
